package com.aacar.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.aacar.constant.ConsFiled;
import com.aacar.dto.Header;
import com.aacar.dto.ImageDto;
import com.aacar.interceptor.MemLoginKeyValid;
import com.aacar.service.UploadHeadUrlService;
import com.aacar.utils.DateUtil;
import com.aacar.utils.ErrorCodeConsField;
import com.aacar.utils.ErrorInfoUtil;
import com.aacar.utils.Pphconfig;
import com.aacar.utils.ResultInfoUtil;
import com.aacar.vo.CommonVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 上传图片
 * @author 王辉
 *
 */
@RestController
@RequestMapping("/imgupload")
public class UploadImageController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private UploadHeadUrlService uploadHeadUrlService;
	
	@RequestMapping("/upload/0")
	@ResponseBody
	@MemLoginKeyValid
	public Object fileUpload(@RequestHeader(value="mobilehead") String mobilehead,@RequestBody ImageDto imageDto) {
		logger.info("request:/imgupload/upload/0"+JSONObject.toJSONString(imageDto));
		BASE64Decoder decoder = new BASE64Decoder();
		String path = "";
		if(imageDto.getFlag().equals(ConsFiled.Upload_Flag_1)) {
			path = Pphconfig.getContextProperty(ConsFiled.Upload_user);
		}else if(imageDto.getFlag().equals(ConsFiled.Upload_Flag_2)){
			path = Pphconfig.getContextProperty(ConsFiled.Upload_wash);
		}
		Header header = null;
		if(null != mobilehead) {
			header = JSON.parseObject(mobilehead, Header.class);
		}
		if(null == imageDto.getFlag()) {
			return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10404, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10404),header.getService());
		}
		CommonVo cv = new CommonVo();
		try {
			byte[] b = decoder.decodeBuffer(imageDto.getBase64Code());
			for (int i = 0; i<b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			StringBuffer sbf = new StringBuffer();
			sbf.append(header.getUserId()).append("=").append(System.currentTimeMillis()).append(".jpg");
			String fileName = sbf.toString();
			File f = new File(path);
			if(!f.exists()) {
				f.mkdirs();
			}
			OutputStream out = new FileOutputStream(path+"/"+fileName);
			out.write(b);
			out.flush();
			out.close();
			//写入数据库
			//车主
			String domain = Pphconfig.getContextProperty(ConsFiled.ROOT_PATH);
			String userPath = Pphconfig.getContextProperty(ConsFiled.ROOT_user_url);
			String washPath = Pphconfig.getContextProperty(ConsFiled.ROOT_wash_url);
			String headUrl = "";
			if(imageDto.getFlag().equals(ConsFiled.Upload_Flag_1)) {
				headUrl = domain+userPath+fileName;
			}else if(imageDto.getFlag().equals(ConsFiled.Upload_Flag_2)){
				headUrl = domain+washPath+fileName;
			}
			imageDto.setUserId(header.getUserId());
			imageDto.setHeadUrl(headUrl);
			uploadHeadUrlService.saveHeader(imageDto);
			cv.setSuccess(true);
			cv.setInfo(headUrl);
		}catch(Exception e) {
			logger.error("上传失败:-----"+e.getMessage());
			return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10403, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10403),header.getService());
		}
		return ResultInfoUtil.setSuccessInfo(cv,header.getService());
	}
	
	/** 
	 * 上传文件 
	 * @param file 
	 * @param request 
	 * @param map 
	 * @return 
	 */  
	@ResponseBody
	@RequestMapping(value = "uploadForm")
	public String uploadMethod(@RequestParam("file") MultipartFile file, HttpServletRequest request,String flag) {
		String path = Pphconfig.getContextProperty(ConsFiled.Upload_user);
		if (!file.isEmpty()) {
			BASE64Encoder encoder = new BASE64Encoder();
			// 通过base64来转化图片
			try {
				String data = encoder.encode(file.getBytes());
				BASE64Decoder decoder = new BASE64Decoder();
				byte[] b = decoder.decodeBuffer(data);
				for (int i = 0; i < b.length; ++i) {
					if (b[i] < 0) {
						b[i] += 256;
					}
				}
				OutputStream out = new FileOutputStream(path);
				out.write(b);
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
